#!/bin/bash

if ! command -v "inotifywait" &> /dev/null; then
     sudo apt-get install -y inotify-tools
fi

# 关闭正在运行的服务
echo 'stop swoole'

if ps -ef | grep -v grep | grep "GPAPI" > /dev/null; then
    ps aux | grep 'GPAPI' | grep -v grep | awk '{print $2}' | sudo xargs kill
fi

sleep 5

if ps -ef | grep -v grep | grep "GPAPI" > /dev/null; then
    echo "stop fail"
else
    echo "stop success"
fi

# 启动服务
php ./public/server.php &

if ps -ef | grep -v grep | grep "GPAPI" > /dev/null; then
    echo "start success"
else
    echo "start fail"
fi

echo 'start watcher'

# 使用inotify等待事件
inotifywait -mrq --format '%w%f' -e create,delete,move,modify,attrib "." --exclude '(\.git/|\.idea/)' |
    while read FILE
    do
        echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        echo "File '$FILE' was modified, reloading..."
        # 进行swoole reload
        ps aux | grep 'GPAPI' | grep -v grep | awk '{print $2}' | sudo xargs kill -USR1
        echo "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
    done